import { CoreConst } from '@ibiz-template/core';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import { setCookie } from 'qx-util';
import { useNamespace } from '@ibiz-template/vue3-util';
import { useRoute } from 'vue-router';
import './login-view.scss';

interface LoginData {
  username: string;
  password: string;
}

const rules = {
  username: [
    {
      required: true,
      message: '请输入账号',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      type: 'string',
      min: 6,
      message: '密码长度不能少于6位',
      trigger: 'blur',
    },
  ],
};

export const LoginView = defineComponent({
  setup() {
    const ns = useNamespace('login-view');

    const loginData = reactive<LoginData>({
      username: '',
      password: '',
    });

    const formRef = ref<IData | null>(null);

    const route = useRoute();
    const ru = (route.query.ru as string) || '/';

    onMounted(() => {
      setTimeout(() => {
        const el = document.getElementById('app-loading-x') as HTMLDivElement;
        if (el) {
          el.style.display = 'none';
        }
      }, 300);
    });

    const loading = ref(false);

    ibiz.appData = undefined;
    ibiz.orgData = undefined;

    const onClick = async () => {
      formRef.value!.validate(async (vaild: boolean) => {
        if (vaild) {
          try {
            loading.value = true;
            const res = await ibiz.auth.v7login(
              loginData.username,
              loginData.password,
            );
            if (res.ok) {
              const { data } = res;
              if (data && data.token) {
                setCookie(CoreConst.TOKEN, data.token, 0, true);
                const expiredDate =
                  new Date().getTime() + (data.expirein || 7199) * 1000;
                setCookie(CoreConst.TOKEN_EXPIRES, `${expiredDate}`, 0, true);
                window.location.hash = ru;
                window.location.reload();
                return;
              }
            }
            ibiz.notification.error({
              title: res.data?.message || '登录失败',
            });
            loading.value = false;
          } catch (error) {
            ibiz.notification.error({
              title: (error as IData).response?.data?.message || '登录失败',
            });
            loading.value = false;
          }
        }
      });
    };

    // 支持enter登录
    const onKeyUp = (e: KeyboardEvent) => {
      if (e.key === 'Enter') {
        onClick();
      }
    };

    return () => (
      <div class={ns.b()}>
        <div class={ns.b('box')}>
          <header class={ns.b('box-header')}>
            <img src='./assets/images/login-header.png' />
          </header>
          <main class={ns.b('box-main')}>
            <img
              class={ns.be('box-main', 'avatar')}
              src='./assets/images/login-avatar.png'
            />
            <div class={ns.b('box-main-content')}>
              <el-form model={loginData} rules={rules} ref={formRef}>
                <el-form-item size='large' prop='username'>
                  <el-input
                    v-model={loginData.username}
                    clearable
                    placeholder='请输入账号'
                    onKeyup={(e: KeyboardEvent) => onKeyUp(e)}
                  >
                    {{
                      prefix: () => <ion-icon name='person'></ion-icon>,
                    }}
                  </el-input>
                </el-form-item>
                <el-form-item size='large' prop='password'>
                  <el-input
                    type='password'
                    v-model={loginData.password}
                    show-password
                    placeholder='请输入密码'
                    onKeyup={(e: KeyboardEvent) => onKeyUp(e)}
                  >
                    {{
                      prefix: () => <ion-icon name='unlock-alt'></ion-icon>,
                    }}
                  </el-input>
                </el-form-item>
                <el-form-item size='large'>
                  <el-button
                    type='primary'
                    onClick={onClick}
                    size='large'
                    round
                    loading={loading.value}
                  >
                    登录
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </main>
        </div>
      </div>
    );
  },
});
